package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * Selector5类
 * 实现选择器5的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class Selector5 implements AxdrType {

    private byte[] dataCode = null;
    private Date_time_s dts = null;
    private MS ms = null;

    public Selector5() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(Date_time_s dts, MS ms) {
        this.dts = dts;
        this.ms = ms;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        dts = new Date_time_s();
        codeLength += dts.decode(input);

        ms = new MS();
        codeLength += ms.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(this.dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (this.dts != null && this.ms != null) {
                codeLength = 0;
                codeLength += this.ms.encode(output);
                codeLength += this.dts.encode(output);
            } else {
                throw new RuntimeException("dts or ms is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    /**
     * 获取日期时间
     * 
     * @return 日期时间
     */
    public Date_time_s getDts() {
        return dts;
    }

    /**
     * 获取成员集
     * 
     * @return 成员集
     */
    public MS getMs() {
        return ms;
    }

    @Override
    public String toString() {
        if (this.dts != null && this.ms != null) {
            return "sequence: {" + "dts: " + this.dts + ", ms: " + this.ms + "}";
        } else {
            return "dts or ms is null";
        }
    }
}